package com.djmw.mouse.web.hr;

import java.util.Date;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.validation.Valid;
import javax.validation.Validator;

import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import com.djmw.mouse.Env;
import com.djmw.mouse.entity.Company;
import com.djmw.mouse.entity.HrUser;
import com.djmw.mouse.entity.Position;
import com.djmw.mouse.entity.PositionHistory;
import com.djmw.mouse.service.ApplicationService;
import com.djmw.mouse.service.CompanyService;
import com.djmw.mouse.service.DepartmentService;
import com.djmw.mouse.service.PositionHistoryService;
import com.djmw.mouse.service.PositionService;
import com.djmw.mouse.service.PositionTypeService;
import com.djmw.mouse.service.account.HrAccountService;
import com.djmw.mouse.service.account.ShiroDbRealm.ShiroUser;
import com.djmw.mouse.service.constants.Constants;
import com.google.common.collect.Maps;

/**
 * 职位管理的Controller, 使用Restful风格的Urls:
 * 
 * List page : GET /hr/position <br>
 * Create page : GET /hr/create <br>
 * Create action : POST /hr/position/create <br>
 * Update page : GET /hr/position/update/{id} <br>
 * Update action : POST /hr/position/update <br>
 * Delete action : GET /hr/position/delete/{id} <br>
 * Enable action : GET /hr/position/enable/{id} <br>
 * Disable action : GET /hr/position/disable/{id} <br>
 * List history page: GET /hr/position/{id}/history <br>
 * List CV page: GET /hr/position/{id}/cv <br>
 * 
 * @author michael
 */

@Controller
@RequestMapping(value = "/hr/position")
public class PositionController {

    private static final int PAGE_SIZE = 50;

    private static Map<String, String> sortTypes = Maps.newLinkedHashMap();
    static {
        sortTypes.put("auto", "自动");
        sortTypes.put("name", "职位名称");
        // sortTypes.put("department", "部门");
        sortTypes.put("publishDate", "发布日期");
        sortTypes.put("freshDate", "刷新日期");
        sortTypes.put("closeDate", "结束日期");
    }

    @Autowired
    private PositionService positionService;
    @Autowired
    private PositionTypeService positionTypeService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private HrAccountService hrAccountService;
    @Autowired
    private PositionHistoryService positionHistoryService;
    @Autowired
    private ApplicationService applicationService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private Validator validator;
    @Autowired
    private Env env;

    @RequestMapping(value = "")
    public String list(@RequestParam(value = "sortType", defaultValue = "auto") String sortType,
            @RequestParam(value = "sortDir", defaultValue = "a") String sortDir,
            @RequestParam(value = "page", defaultValue = "1") int pageNumber, Model model, ServletRequest request) {
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        Page<Position> positions = positionService.getCompanyPosition(getCurrentUser().getCompany().getId(),
                searchParams, pageNumber, PAGE_SIZE, sortType, sortDir);

        model.addAttribute("positions", positions);
        model.addAttribute("sortType", sortType);
        model.addAttribute("sortTypes", sortTypes);
        model.addAttribute("provinces", Constants.PROVINCES);
        model.addAttribute("cities", Constants.CITIES);
        // 将搜索条件编码成字符串，用于排序，分页的URL
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));

        return "hr/position/position-list";
    }

    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String createForm(Model model) {
        model.addAttribute("position", new Position());
        Company company = getCurrentUser().getCompany();
        model.addAttribute("companyId", company.getId());
        model.addAttribute("companyName", company.getName());
        model.addAttribute("departments", departmentService.getAllCompanyDepartment(company.getId()));
        model.addAttribute("provinces", Constants.PROVINCES);
        model.addAttribute("cities", Constants.CITIES);
        model.addAttribute("languages", Constants.LANGUAGES);
        model.addAttribute("proficiencys", Constants.PROFICIENCYS);
        model.addAttribute("action", "create");
        model.addAttribute("educations", Constants.EDUCATIONS);
        model.addAttribute("workingYears", Constants.WORKING_YEARS);
        model.addAttribute("majors", Constants.MAJORS);
        model.addAttribute("salaryRanges", Constants.SALARY_RANGES);
        model.addAttribute("jobTypes", Constants.JOB_TYPES);
        return "hr/position/position-form";
    }

    @RequestMapping(value = "create", method = RequestMethod.POST)
    public String create(@Valid Position position, Long companyId, Long departmentId, Long positionTypeId,
            Long positionType2Id, RedirectAttributes redirectAttributes) {
        Company company = companyService.getCompany(companyId);
        position.setCompany(company);
        if (departmentId != null) {
            position.setDepartment(departmentService.getDepartment(departmentId));
        }
        position.setPosType(positionTypeService.getPosition(positionTypeId));
        if (positionType2Id != null) {
            position.setPosType2(positionTypeService.getPosition(positionType2Id));
        }
        Date now = new Date();
        position.setPublishDate(now);
        position.setRefreshDate(now);
        position.setCloseDate(DateUtils.addMonths(now, 2));
        positionService.savePosition(position, getCurrentUser());
        redirectAttributes.addFlashAttribute("message", "创建职位成功");
        return "redirect:/hr/position/";
    }

    @RequestMapping(value = "update/{id}", method = RequestMethod.GET)
    public String updateForm(@PathVariable("id") Long id, Model model) {
        Position position = positionService.getPosition(id);
        model.addAttribute("position", position);
        Company company = position.getCompany();
        model.addAttribute("companyId", company.getId());
        model.addAttribute("companyName", company.getName());
        model.addAttribute("departments", departmentService.getAllCompanyDepartment(company.getId()));
        model.addAttribute("provinces", Constants.PROVINCES);
        model.addAttribute("cities", Constants.CITIES);
        model.addAttribute("languages", Constants.LANGUAGES);
        model.addAttribute("proficiencys", Constants.PROFICIENCYS);
        model.addAttribute("action", "create");
        model.addAttribute("educations", Constants.EDUCATIONS);
        model.addAttribute("workingYears", Constants.WORKING_YEARS);
        model.addAttribute("majors", Constants.MAJORS);
        model.addAttribute("salaryRanges", Constants.SALARY_RANGES);
        model.addAttribute("jobTypes", Constants.JOB_TYPES);
        model.addAttribute("action", "update");
        return "hr/position/position-form";
    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String update(@Valid @ModelAttribute("preloadPosition") Position position, Long companyId,
            Long departmentId, Long positionTypeId, Long positionType2Id, RedirectAttributes redirectAttributes) {
        Company company = companyService.getCompany(companyId);
        position.setCompany(company);
        if (departmentId != null) {
            position.setDepartment(departmentService.getDepartment(departmentId));
        }
        position.setPosType(positionTypeService.getPosition(positionTypeId));
        if (positionType2Id != null) {
            position.setPosType2(positionTypeService.getPosition(positionType2Id));
        }
        positionService.savePosition(position, getCurrentUser());
        redirectAttributes.addFlashAttribute("message", "更新职位成功");
        return "redirect:/hr/position/";
    }

    @RequestMapping(value = "delete/{id}")
    public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
        positionService.deletePosition(id, getCurrentUser());
        redirectAttributes.addFlashAttribute("message", "删除职位成功");
        return "redirect:/hr/position/";
    }

    /**
     * 使用@ModelAttribute, 实现Struts2Preparable二次部分绑定的效果. <br>
     * 先根据form的id从数据库查出Position对象,再把Form提交的内容绑定到该对象上. <br>
     * 因为仅update()方法的form中有id属性，因此本方法在该方法中执行.
     */
    @ModelAttribute("preloadPosition")
    public Position getDepartment(@RequestParam(value = "id", required = false) Long id) {
        if (id != null) {
            return positionService.getPosition(id);
        }
        return null;
    }

    public HrUser getCurrentUser() {
        ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
        // HrUser hrUser = hrAccountService.getUser(user.id);
        HrUser hrUser = (HrUser) user.getUser();
        return hrUser;
    }

    @RequestMapping(value = "{id}/history")
    public String history(@PathVariable("id") Long id,
            @RequestParam(value = "sortDir", defaultValue = "d") String sortDir,
            @RequestParam(value = "page", defaultValue = "1") int pageNumber, Model model, ServletRequest request) {
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        Page<PositionHistory> history = positionHistoryService.getPositionHistory(id, searchParams, pageNumber,
                PAGE_SIZE, sortDir);

        model.addAttribute("historys", history);
        model.addAttribute("sortType", "auto");
        model.addAttribute("sortTypes", sortTypes);
        // 将搜索条件编码成字符串，用于排序，分页的URL
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));

        return "hr/position/history-list";
    }

    @RequestMapping(value = "{id}/history/{hid}", method = RequestMethod.GET)
    public String historyDetail(@PathVariable("id") Long pid, @PathVariable("hid") Long hid, Model model) {
        PositionHistory history = positionHistoryService.getPositionHistory(hid);
        model.addAttribute("history", history);
        Company company = history.getCompany();
        model.addAttribute("departments", departmentService.getAllCompanyDepartment(company.getId()));
        model.addAttribute("provinces", Constants.PROVINCES);
        model.addAttribute("cities", Constants.CITIES);
        model.addAttribute("languages", Constants.LANGUAGES);
        model.addAttribute("proficiencys", Constants.PROFICIENCYS);
        model.addAttribute("action", "create");
        model.addAttribute("educations", Constants.EDUCATIONS);
        model.addAttribute("workingYears", Constants.WORKING_YEARS);
        model.addAttribute("majors", Constants.MAJORS);
        model.addAttribute("salaryRanges", Constants.SALARY_RANGES);
        model.addAttribute("jobTypes", Constants.JOB_TYPES);
        model.addAttribute("action", "update");
        return "hr/position/history-detail";
    }

    @RequestMapping(value = "refresh/{id}", method = RequestMethod.GET)
    public String refresh(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
        positionService.refresh(id, getCurrentUser());
        return "redirect:/hr/position/";
    }

    @RequestMapping(value = "enable/{id}")
    public String enable(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
        positionService.enablePosition(id, getCurrentUser());
        redirectAttributes.addFlashAttribute("message", "启用职位成功");
        return "redirect:/hr/position/";
    }

    @RequestMapping(value = "disable/{id}")
    public String disable(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
        positionService.disablePosition(id, getCurrentUser());
        redirectAttributes.addFlashAttribute("message", "暂停职位成功");
        return "redirect:/hr/position/";
    }

    @RequestMapping(value = "copy/{id}")
    public String copy(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
        positionService.copyPosition(id, getCurrentUser());
        redirectAttributes.addFlashAttribute("message", "再发布职位成功");
        return "redirect:/hr/position/";
    }

    public static int PAGE_SIZE_CV_PER_PAGE = 20;

    @RequestMapping(value = "{id}/cv")
    public String cv(@PathVariable("id") Long id,
            @RequestParam(value = "sortType", defaultValue = "createDate") String sortType,
            @RequestParam(value = "sortDir", defaultValue = "d") String sortDir,
            @RequestParam(value = "page", defaultValue = "1") int pageNumber,
            @RequestParam(value = "pageSize", defaultValue = "0") int pageSize,
            Model model, ServletRequest request, RedirectAttributes redirectAttributes) {
        return "redirect:/hr/application?positionId=" + id;
        /*
         * Map<String, Object> searchParams =
         * Servlets.getParametersStartingWith(request, "search_"); HrUser hrUser
         * = getCurrentUser(); Position position =
         * positionService.getPosition(id); if (position == null) {
         * redirectAttributes.addFlashAttribute("message", "无此职位"); return
         * "redirect:/hr/position/"; } if (position.getCompany().getId() !=
         * hrUser.getCompany().getId()) {
         * redirectAttributes.addFlashAttribute("message", "无权查看"); return
         * "redirect:/hr/position/"; } if (pageSize == 0) { pageSize =
         * env.getPageSize().getHrAppPageSize(); } Page<Application>
         * applications = applicationService.getApplicationByPositionId(id,
         * searchParams, pageNumber, pageSize, sortType, sortDir);
         * model.addAttribute("positionId", id);
         * model.addAttribute("applications", applications);
         * model.addAttribute("sortType", sortType);
         * model.addAttribute("sortTypes", sortTypes); //
         * 将搜索条件编码成字符串，用于排序，分页的URL model.addAttribute("searchParams",
         * Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
         * return "hr/application/application-list";
         */
    }
}
